package com.sumainfor.wx.tenant.util;

import com.sumainfor.common.wechat.Jsapi_ticketUtil;
import com.sumainfor.common.wechat.WeChatConfig;

/**
 * @Author Eddy·Chen
 * @Email 835033913@qq.com
 * @Create 2019-03-06 15:32
 */
public class WeChartUtil {
    /**
     * 缓存的access_token
     */
    private static String accessToken;
    /**
     * access_token的失效时间
     */
    private static long expiresTime;

    /**
     * 获取access_token的接口地址
     */
    public static final String GET_ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * 获取accessToken
     *
     * @return
     */
    public static String getAccessToken() {
        //判断accessToken是否已经过期，如果过期需要重新获取
        if (accessToken == null || expiresTime < System.currentTimeMillis()) {
            // 获取公众号access_token的链接
            String access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

            String requestUrl = access_token.replace("APPID", WeChatConfig.APP_ID).replace("APPSECRET", WeChatConfig.APP_SECRET);

            net.sf.json.JSONObject jsonObject = Jsapi_ticketUtil.httpRequest(requestUrl, "GET", null);

            //缓存accessToken
            accessToken = jsonObject.getString("access_token");
            //设置accessToken的失效时间
            long expires_in = jsonObject.getLong("expires_in");
            //失效时间 = 当前时间 + 有效期(提前一分钟)
            expiresTime = System.currentTimeMillis() + (expires_in - 60) * 1000;
        }
        return accessToken;
    }

}
